package Negocio;

import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import Objetos.Aeropuertos;


public class negAeropuerto {

	public void escribeAeropuerto(String nombre, String file)throws IOException, ClassNotFoundException{
		try{	
			  ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
			  Aeropuertos aero = new Aeropuertos(1, 1 ,nombre);
			  oos.writeObject(aero);	    	    
			 
	          oos.close(); 
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	
	public void agregaAeropuerto(String nombre, String file){
	    try{
	    	int id = ObtenerUltimoId(file);
	            MiObjectOutputStream oos = new MiObjectOutputStream(new FileOutputStream(file,true));
	            Aeropuertos aero = new Aeropuertos(id + 1, 1 ,nombre);	               
	            oos.writeUnshared(aero);	            
	            oos.close();
	        } catch (Exception e)
	        {
	            e.printStackTrace();
	        }
	    }
		
	public  ArrayList<Aeropuertos> leerAeropuerto(String file)throws IOException, ClassNotFoundException { 
			ArrayList<Aeropuertos> aero = new ArrayList<Aeropuertos>();
		try{   
	        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); 
	        Object aux = ois.readObject();        
	        while (aux!=null)
	        {
	        	aero.add((Aeropuertos)aux);
			    aux = ois.readObject();
	        }
	        ois.close();        
	        return aero;                  
	    }
	    catch (EOFException e1)
	    {
	       return aero;        
	   }    	
}
	private int ObtenerUltimoId(String file)throws IOException, ClassNotFoundException{		
		ObjectInputStream ois = null;
		int count = 0;
		try{
			ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));			
			Object aux = ois.readObject();        
	        while (aux!=null)
	        {
	        	count ++;
			    aux = ois.readObject();
	        }						
		return count;
		}catch(EOFException e){		
			return(count);
		}		
	}	
	
	
}
